package com.heaven.back.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heaven.back.WebSocket.WebSocketUtil;
import com.heaven.back.mapper.ActionMapper;
import com.heaven.back.mapper.ChatMapper;
import com.heaven.back.mapper.RefreshMapper;
import com.heaven.back.pojo.Player;
import com.heaven.back.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * The type Chat serviceimpl.
 */
@Service
public class ChatServiceimpl implements ChatService {

    @Autowired
    private RefreshMapper refreshMapper;

    @Autowired
    private ActionMapper actionMapper;

    @Autowired
    private ChatMapper chatMapper;

    @Override
    public void sendMessage(Integer id, String msg, Integer type) throws Exception {
        Player e = actionMapper.searchByid(id);
        switch (type) {
            case 0: {
                ArrayList<Integer> ids = chatMapper.getids();
                for (int i = 0; i < ids.size(); i++) {
                    Player p = actionMapper.searchByid(ids.get(i));
                    if (p.isLogin()) {
                        Map msgMap = new HashMap();
                        msgMap.put("type", "arp");
                        msgMap.put("msg", msg);
                        msgMap.put("id", id);
                        WebSocketUtil.sendInfo(JSONObject.toJSONString(msgMap), ids.get(i));
                    }
                }

                break;
            }
            case 1: {
                ArrayList<Integer> ids = refreshMapper.getidsByRoomName(e.getCurrentRoom());
                for (int i = 0; i < ids.size(); i++) {
                    Player p = actionMapper.searchByid(ids.get(i));
                    if (p.isLogin()) {
                        Map msgMap = new HashMap();
                        msgMap.put("type", "arp");
                        msgMap.put("msg", msg);
                        msgMap.put("id", id);
                        WebSocketUtil.sendInfo(JSONObject.toJSONString(msgMap), ids.get(i));
                    }
                }
                break;
            }
        }
    }
}
